package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;

	//分页查询用户
    @GetMapping()
    public Result selectByPage(@RequestParam  int currentPage,@RequestParam int pageSize) throws IOException {
        IPage<User> userPage = new Page<>(currentPage,pageSize);
        userMapper.selectPage(userPage,null);
        System.out.println(userPage.getRecords());
        if (userPage!=null){
            return  new Result(20041,userPage.getRecords());
        }else {
            return new Result(20040,"查询失败");
        }

    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        int insert = userMapper.insert(user);
        if (insert!=0){
            return  new Result(20011,"success");
        }else {
            return new Result(20010,"添加失败");
        }

    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userMapper.deleteById(id);
        if (i!=0){
            return new Result(20021,"success");
        }else {
            return new Result(20020,null,"删除失败");
        }

    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        int i = userMapper.updateById(user);
        if (i!=0){
            return new Result(20031,"success");
        }else {
            return new Result(20030,null,"修改失败");
        }
    }

}
